package com.qiwx.pigeon.activity.stock;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.andview.refreshview.XRefreshView;
import com.avast.android.dialogs.iface.ISimpleDialogListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.Utils.LogUtil;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.activity.MainActivity;
import com.qiwx.pigeon.adapter.produce.GetOutReccordAdapter;
import com.qiwx.pigeon.app.AppContext;
import com.qiwx.pigeon.base.BaseMVPActivity;
import com.qiwx.pigeon.data.EnumGetOut;
import com.qiwx.pigeon.data.network.BaseResponse;
import com.qiwx.pigeon.data.params.GoOutParam;
import com.qiwx.pigeon.data.vo.EmployBean;
import com.qiwx.pigeon.data.vo.GoOutBean;
import com.qiwx.pigeon.data.vo.pageinfo.PageInfo;
import com.qiwx.pigeon.helper.DialogHelper;
import com.qiwx.pigeon.presenter.GoOutPresenter;
import com.qiwx.pigeon.viewinterface.IGoOutView;
import com.qiwx.pigeon.widget.ArrowView;
import com.qiwx.pigeon.widget.itemderection.LineItemDecoration;

import org.angmarch.views.NiceSpinner;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @description
 * @Author qiwx
 * @Date 2020/8/24 9:38 PM
 * 出栏商品
 **/
public class GetOutManagerActivity extends BaseMVPActivity<IGoOutView, GoOutPresenter> implements IGoOutView, ISimpleDialogListener {
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_return)
    ArrowView titleReturn;
    @BindView(R.id.title_right)
    TextView titleRight;
    @BindView(R.id.llTitle)
    LinearLayout llTitle;
    @BindView(R.id.sp_pigeon)
    NiceSpinner spPigeon;
    @BindView(R.id.txt_start_date)
    TextView txtStartDate;
    @BindView(R.id.edt_getout_amount)
    EditText edtGetoutAmount;
    @BindView(R.id.lin1)
    LinearLayout lin1;
    @BindView(R.id.btn_add)
    Button btnAdd;
    @BindView(R.id.txt_nodata)
    TextView txtNodata;
    @BindView(R.id.lin_nodata)
    LinearLayout linNodata;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.xRefreshView)
    XRefreshView xRefreshView;
    @BindView(R.id.rel_nodata_recycleview)
    RelativeLayout relNodataRecycleview;
    EnumGetOut currentGetOut;
    GetOutReccordAdapter adapter;
    List<GoOutBean> data = new ArrayList<>();
    GoOutParam getOutParam;
    List<Integer> wh_ids = new ArrayList<>();
    int pageNum = 1;
    int pageSize = 20;
    boolean isFresh = true;
    int currentPos = 0;
    int DELETE_GO_OUT_REQUEST = 1001;

    @Override
    public GoOutPresenter createPresenter() {
        return new GoOutPresenter(new WeakReference(this));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_stock_getout;
    }

    @Override
    public void initAfterOnCreate() {
        titleReturn.changeArrowLeft();
        titleContent.setText("出栏商品列表");
        getOutParam = new GoOutParam();
        wh_ids.add(MainActivity.wh_id);
        getOutParam.setWh_ids(wh_ids);
        EmployBean bean = AppContext.getEmployBean(this);
        if (bean != null) {
            getOutParam.setF_id(bean.getF_id());
        }
        getOutParam.setPageSize(pageSize);
        initView();
        initSpinner();
        loadData(true);
    }

    private void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(linearLayoutManager);
        recyclerview.addItemDecoration(new LineItemDecoration(2));
        xRefreshView.setHideFooterWhenComplete(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                loadData(true);

            }

            @Override
            public void onLoadMore(boolean isSilence) {
                pageNum++;
                loadData(false);
            }
        });

    }

    public void initSpinner() {
        EnumGetOut[] enums = EnumGetOut.values();
        List<String> data = new ArrayList<>();
        for (EnumGetOut item : enums) {
            data.add(item.getName());
        }
        if (enums.length > 0) {
            currentGetOut = enums[0];
        }
        spPigeon.attachDataSource(data);
        spPigeon.setOnSpinnerItemSelectedListener((parent, view, position, id) -> {
            currentGetOut = enums[position];
            LogUtil.e("TAG", currentGetOut.getName());
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    //查询出栏记录
    public void loadData(boolean isFresh) {
        this.isFresh = isFresh;
        if (isFresh) {
            data.clear();
            pageNum = 1;
        }
        getOutParam.setPageNum(pageNum);
        mPresenter.getGoOutRecordList(getOutParam);
    }

    //出栏操作
    public void addGetOut() {
        //先判断鸽仓是否存在
        if (MainActivity.wh_id <= 0) {
            MyToast.showLong("鸽仓编号不正确，请选择正确鸽仓编号！");
            return;
        }

        String strAmount = edtGetoutAmount.getText().toString();
        if (strAmount.equals("") || strAmount == null) {
            MyToast.showLong("请添加出栏数量");
            return;
        }
        int amount = 0;
        try {
            amount = Integer.valueOf(strAmount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (amount == 0) {
            MyToast.showLong("请添正确数量");
            return;
        }
//        String startDate = txtStartDate.getText().toString();
//        startDate += " " + DateTimeUtils.getCurrentTime();
//        long date = DateTimeUtils.date2TimeStamp(startDate);

        GoOutBean bean = new GoOutBean();
        bean.setGoout_date(DateTimeUtils.getCurrentDateStr());
        bean.setAmount(amount);
        bean.setType(currentGetOut.getType());
        bean.setOperate_time(DateTimeUtils.timeStamp2DateTime(new Date().getTime()));
        bean.setWh_id(MainActivity.wh_id);
        mPresenter.addGoOut(bean);


    }

    private void showRecord(PageInfo<GoOutBean> bean) {
        data.addAll(bean.getList());
        if (isFresh) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
            if (!bean.isHasNextPage()) {
                MyToast.showLong("没有更多数据了");
            }
        }
        if (!bean.isHasNextPage()) {
            xRefreshView.setPullLoadEnable(false);
        } else {
            xRefreshView.setPullLoadEnable(true);
        }

        if (data == null || data.size() == 0) {
            txtNodata.setVisibility(View.VISIBLE);
            recyclerview.setVisibility(View.GONE);
        } else {
            txtNodata.setVisibility(View.GONE);
            recyclerview.setVisibility(View.VISIBLE);
            if (adapter == null) {
                adapter = new GetOutReccordAdapter(R.layout.adapter_getout_reccord_item, data);
                recyclerview.setAdapter(adapter);
                adapter.setOnItemLongClickListener(new OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                        DialogHelper.showCommonDialog(GetOutManagerActivity.this, "确定要删除此记录么?", DELETE_GO_OUT_REQUEST);

                        return false;
                    }
                });
            } else {
                adapter.notifyDataSetChanged();
            }
        }

    }

    @OnClick({R.id.title_return, R.id.txt_start_date, R.id.btn_add, R.id.txt_nodata, R.id.recyclerview})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_return:
                finish();
                break;
            case R.id.txt_start_date:
                break;
            case R.id.btn_add:
                addGetOut();
                break;
            case R.id.txt_nodata:
                break;
            case R.id.recyclerview:
                break;
        }
    }

    @Override
    public void onAddGoOutSuccess(BaseResponse response) {
        loadData(true);
    }

    @Override
    public void onGoOutListSuccess(PageInfo<GoOutBean> list) {
        showRecord(list);
    }

    @Override
    public void onDeleteGoOutSuccess(BaseResponse response) {
        MyToast.showCenterShort("删除成功");
        data.remove(currentPos);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onFailed(String error) {

    }

    @Override
    public void onNegativeButtonClicked(int requestCode) {

    }

    @Override
    public void onNeutralButtonClicked(int requestCode) {

    }

    //dialog 确定
    @Override
    public void onPositiveButtonClicked(int requestCode) {
        if (requestCode == DELETE_GO_OUT_REQUEST) {
            mPresenter.deleteGoOut(data.get(currentPos));
        }

    }
}
